/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.lock.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;

import com.iiifi.kite.core.util.Charsets;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * RedisLock
 *
 * @author kite@iiifi.com 花朝
 **/
@Slf4j
@AllArgsConstructor
public class RedisLockClient {

    private RedisTemplate<String, Object> redisTemplate;

    private static final String UNLOCK_LUA;

    /**
     * 释放锁脚本，原子操作
     */
    static {
        StringBuilder sb = new StringBuilder();
        sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
        sb.append("then ");
        sb.append("    return redis.call(\"del\",KEYS[1]) ");
        sb.append("else ");
        sb.append("    return 0 ");
        sb.append("end ");
        UNLOCK_LUA = sb.toString();
    }

    public boolean lock(String key, String requestId, long expire, TimeUnit timeUnit) {
        try {
            RedisCallback<Boolean> callback = (connection) -> connection.set(key.getBytes(Charsets.UTF_8),
                    requestId.getBytes(Charsets.UTF_8), Expiration.seconds(timeUnit.toSeconds(expire)),
                    RedisStringCommands.SetOption.SET_IF_ABSENT);
            Boolean res = redisTemplate.execute(callback);
            return res != null && res;
        } catch (Exception e) {
            log.error("redis lock error.", e);
        }
        return false;
    }

    public void unlock(String key, String requestId) {
        RedisCallback<Boolean> callback = (connection) -> connection.eval(UNLOCK_LUA.getBytes(), ReturnType.BOOLEAN, 1,
                key.getBytes(Charsets.UTF_8), requestId.getBytes(Charsets.UTF_8));
        redisTemplate.execute(callback);
    }

    public boolean isLocked(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        return o != null;
    }
}
